import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入子组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/users/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Param from '../components/goods/Param.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'

// 注册全局 路由构造函数
Vue.use(VueRouter)

// 定义路由规则数组
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/Rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/Params', component: Param },
      { path: '/goods', component: List },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Order }

    ]
  }
]

// 创建路由表对象
const router = new VueRouter({
  routes
})

// 设置路由守卫
// 作用:在浏览器地址栏的hash值发生改变时触发，可以用来检查当前访问的hash路径是否需要有token
router.beforeEach((to, from, next) => {
  // 判断访问的是否为login，如果是则放行
  if (to.path === '/login') return next()
  // 否则，尝试获取内存中的token值
  const strToken = window.sessionStorage.getItem('token')
  // 如果不存在token，则强制将路径改为login
  if (!strToken) return next('/login')
  // 如果存在token，则放行
  next()
})

// 导出路由表对象
export default router
